<template>
  <el-table
    :data="
      tableData.filter(
        (data) =>
          !search || data.name.toLowerCase().includes(search.toLowerCase())
      )
    "
    border
    fit
    style="width: 100%"
    :cell-style="{padding: 0}"
    max-height="100%"
    highlight-current-row
    @current-change="handleCurrentChange"
    :summary-method="getSummaries"
    show-summary
    :span-method="objectSpanMethod"
    >
    <el-table-column sortable prop="id" label="Id" width="180" />
    <el-table-column sortable prop="name" label="Name" width="180" />
    <el-table-column sortable prop="amount1" label="Amount1" width="180"/>
    <el-table-column fixed="right" label="Operation">
      <!--至少有一个栏不定义width-->
      <template #header>
        <el-input v-model="search" size="mini" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <el-button
          type="text"
          size="small"
          @click.prevent="deleteRow(scope.$index, tableData)"
        >
          Remove
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts">
import { mapMutations } from "vuex";

export default {
  data() {
    return {
      search: '',
    }
  },

  computed:{
    tableData(){
      return this.$store.state.tableData
    }
  },

  async mounted(){
    console.log(this.tableData)
    const response= await fetch("http://82.156.0.223:3001/data/table", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        token: sessionStorage.getItem('token')
      }),
    });
    var { tableData }  = await response.json();
    this.set_tableData(tableData)
  },
  methods: {
    ...mapMutations(["set_tableData"]),
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    handleCurrentChange(val) {
      this.currentRow = val
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = `（总计）${values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)}`
        } else {
          sums[index] = ''
        }
      })

      return sums
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
    },
  },
}
</script>
